package com.hefeng.unit.common;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hefeng.common.core.utils.DateUtils;
import com.hefeng.common.core.utils.EmptyUtils;
import com.hefeng.common.redis.service.RedisService;
import com.hefeng.unit.domain.GyDeviceReport;
import com.hefeng.unit.domain.GyDeviceUser;
import com.hefeng.unit.domain.entity.UserDto;
import com.hefeng.unit.mapper.GyDeviceReportMapper;
import com.hefeng.unit.mapper.GyDeviceUserMapper;
import com.hefeng.unit.service.GyDeviceReportService;
import com.hefeng.unit.util.Sample;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@SuppressWarnings("ALL")
@Slf4j
@Component
public class MessageListener {
    @Autowired
    GyDeviceReportService gyDeviceReportService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private GyDeviceUserMapper gyDeviceUserMapper;
@Autowired
        private GyDeviceReportMapper gyDeviceReportMapper;


    //报警存储集合
    List<GyDeviceReport> list = new ArrayList<GyDeviceReport>();

    //报警消息接受中心
    @KafkaListener(topics = {"industry_collection_alarm_topic"}, groupId = "collection-group")
    public void listener(ConsumerRecord<String, String> record) {
        try {
            Optional<?> optional = Optional.ofNullable(record.value());
            //获取消息
            String message = record.value();
            JSONObject data = JSONObject.fromObject(message);
            String deviceCode = data.getString("deviceCode");
            String time = String.valueOf(new Date(Long.valueOf(data.getString("messageTime"))));
            Date date = DateUtil.parse(time);
            DateTime newDate3 = DateUtil.offsetHour(date, 8);
            String formatDateTime = DateUtil.formatDateTime(newDate3);



            GyDeviceReport gyDeviceReport = new GyDeviceReport();
            GyDeviceReport gyDeviceRepors = gyDeviceReportMapper.selectByTime(deviceCode);

            if (ObjectUtil.isNotNull(gyDeviceRepors)) {
                long betweenDay = DateUtil.between(date, gyDeviceRepors.getReportTime(), DateUnit.MINUTE);
                if (betweenDay < 3) {
                    return;
                }
            }
            //判断消息是否重复

            GyDeviceUser user=gyDeviceUserMapper.getUser(deviceCode);
            gyDeviceReport.setUserId(user.getUserId());
            gyDeviceReport.setDeviceCode(deviceCode);
            gyDeviceReport.setReportId(IdWorker.getId());
            gyDeviceReport.setReportTitle("燃气泄露报警");
            gyDeviceReport.setReportTime(new Date(Long.valueOf(data.getString("messageTime"))));
            gyDeviceReport.setReportContent("设备在" + DateUtils.getFormatDate(Long.valueOf(data.getString("messageTime"))) + "发生燃气泄露！");
            gyDeviceReport.setReportValue(Double.parseDouble(data.getString("concentration")));
            gyDeviceReport.setReportType("1");
            gyDeviceReport.setIsSmsNotice(0);
            gyDeviceReport.setCreatedTime(new Date());
            gyDeviceReportService.save(gyDeviceReport);
            //发送短信
            Client client = null;
            try {
                //for (int i = 0; i < userDto.getPhone().size(); i++) {
                    client = Sample.createClient("LTAI4G9NUVeKwrPQh9QwPyMh", "P1NuKkn65iCM9YjunAfhCpBIN062Xg");
                    SendSmsRequest sendSmsRequest = new SendSmsRequest()
                            //.setPhoneNumbers(userDto.getPhone().get(i).toString())
                            .setPhoneNumbers(user.getPhone())
                            .setSignName("海南合丰运维科技有限公司")
                            .setTemplateCode("SMS_235814724")
                            .setTemplateParam("{\"time\":\"" + formatDateTime + "\",\"event\":\"" + "燃气泄漏" + "\"}");
                    // 复制代码运行请自行打印 API 的返回值
                    SendSmsResponse sendResp = client.sendSms(sendSmsRequest);
                    String code = sendResp.body.code;
                    if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
                        com.aliyun.teaconsole.Client.log("错误信息: " + sendResp.body.message + "");
                    }
                //}
            } catch (Exception e) {
                e.printStackTrace();
            }
            redisService.setCacheObject(deviceCode, gyDeviceReport);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
